package com.ssh.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ssh.entity.Cart;
import com.ssh.entity.CartItem;
import com.ssh.entity.Product;
import com.ssh.service.ProductService;

@Controller
@RequestMapping("/cart")
public class CartController {

	@Autowired
	private ProductService ps;
	
	/**
	 * 添加购物车
	 * @param req
	 * @param rsp
	 * @return
	 */
	@RequestMapping(value = "/add.do")
	public String addCart(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			// 获取pid和count
			Integer pid = Integer.parseInt(req.getParameter("pid"));
			Integer count = Integer.parseInt(req.getParameter("count"));
			
			Product product = ps.show(pid);
			
			CartItem cartItem = new CartItem(product, count);
			
			Cart cart = getCart(req);
			
			cart.add(cartItem);
			
			rsp.sendRedirect(req.getContextPath() + "/view/shoppingCart.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 移除购物车项
	 * @param req
	 * @param rsp
	 * @return
	 */
	@RequestMapping(value = "/remove.do")
	public String removeCart(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			// 获取pid
			Integer pid = Integer.parseInt(req.getParameter("pid"));
			
			getCart(req).remove(pid);
			
			rsp.sendRedirect(req.getContextPath() + "/view/shoppingCart.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 清空购物车
	 * @param req
	 * @param rsp
	 * @return
	 */
	@RequestMapping(value = "/clear.do")
	public String clearCart(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			getCart(req).clear();
			
			rsp.sendRedirect(req.getContextPath() + "/view/shoppingCart.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取购物车
	 * @param req
	 * @return
	 */
	private Cart getCart(HttpServletRequest req) {
		Cart cart = (Cart)req.getSession().getAttribute("cart");
		if(cart == null){
			cart = new Cart();
			req.getSession().setAttribute("cart", cart);
		}
		return cart;
	}
}
